import { useEffect, useRef } from 'react'
import { Chart } from '@antv/g2'

export default (containerRef, config) => {
  const chartRef = useRef(null)

  useEffect(() => {
    if (!containerRef.current) return

    // 销毁旧实例
    if (chartRef.current) {
      chartRef.current.destroy()
    }

    // 创建新图表
    chartRef.current = new Chart({
      container: containerRef.current,
      autoFit: true,
      ...config.chartOptions,
    })

    // 执行配置函数
    config.configureChart(chartRef.current)

    // 响应式处理
    const resizeObserver = new ResizeObserver(() => {
      chartRef.current?.forceFit()
    })
    resizeObserver.observe(containerRef.current)

    return () => {
      resizeObserver.disconnect()
      chartRef.current?.destroy()
    }
  }, [config])

  return chartRef
}
